package com.ebt.m.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;

import com.ebt.m.AppContext;
import com.ebt.m.AppInitService;
import com.ebt.m.R;
import com.ebt.m.commons.buscomponent.permission.Permission;
import com.ebt.m.commons.buscomponent.permission.RxPermissions;
import com.ebt.m.commons.widgets.view.EBTDialog;
import com.ebt.m.data.bean.UserInfo;
import com.ebt.m.utils.EBTInit;

import java.util.HashMap;
import java.util.Map;

public class IndexActivity extends FragmentActivity {

    private SharedPreferences preferences;
    private Editor editor;
    private RxPermissions permissions;
    private EBTDialog confirmDialog;
    private String appName;
    private Map<String, Permission> allNeadPermissions;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!isTaskRoot()) {
            finish();
            return;
        }
        appName = getResources().getString(R.string.app_name);
        getPermission();
    }

    private void getPermission() {
        if (allNeadPermissions == null)
            allNeadPermissions = new HashMap<>();
        if (permissions == null)
            permissions = new RxPermissions(this);
        permissions
                .requestEach(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE)
                .subscribe(permission -> {
                    allNeadPermissions.put(permission.name, permission);
                    //全部权限请求完毕
                    if (allNeadPermissions.size() == 2) {
                        Permission externalPermission = allNeadPermissions.get(Manifest.permission.WRITE_EXTERNAL_STORAGE);
                        Permission readPhonePermission = allNeadPermissions.get(Manifest.permission.READ_PHONE_STATE);
                        if (externalPermission.granted && readPhonePermission.granted) {
                            EBTInit.init(AppContext.getInstance());
                            AppInitService.getInstance().initService();
                            forwardToAct();
                        } else {
                            allNeadPermissions.clear();
                            Permission deniedPermission = !externalPermission.granted ? externalPermission : readPhonePermission;
                            showConfirmDialog(deniedPermission, !deniedPermission.shouldShowRequestPermissionRationale);
                        }
                    }
                });
    }

    private void showConfirmDialog(Permission permission, boolean gotoSet) {
        if (confirmDialog == null) {
            confirmDialog = new EBTDialog();
            confirmDialog.setCancelable(false);
            confirmDialog.setMessage("我们需要这些权限，为你提供服务；否则，你将无法使用" + appName);
            confirmDialog.setLeftButton("取消", view -> {
                confirmDialog.dismiss();
                IndexActivity.this.finish();
            });
        }

        if (permission != null && permission.name.equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            confirmDialog.setMessage("我们需要获取存储空间权限，为你存储个人信息；否则，你将无法使用" + appName);
        }

        if (permission != null && permission.name.equals(Manifest.permission.READ_PHONE_STATE)) {
            confirmDialog.setMessage("我们需要获取设备信息，为你进行设备识别；否则，你将无法使用" + appName);
        }
        if (gotoSet) {
            confirmDialog.setRightButton("去设置", view -> {
                confirmDialog.dismiss();
                IndexActivity.this.finish();
                Intent localIntent = new Intent();
                localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                localIntent.setData(Uri.fromParts("package", getPackageName(), null));
                startActivity(localIntent);
            });

        } else {
            confirmDialog.setRightButton("确定", view -> {
                confirmDialog.dismiss();
                getPermission();
            });
        }
        confirmDialog.show(getSupportFragmentManager(), getClass().getSimpleName());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (confirmDialog != null) {
            confirmDialog.dismiss();
            confirmDialog = null;
        }

    }

    /**
     * 根据绑定状态及是否初次安装选择跳转页面
     */
    private void forwardToAct() {
        preferences = getSharedPreferences("phone", Context.MODE_PRIVATE);

        if (preferences.getBoolean("firststart", true)) {
            editor = preferences.edit();
            editor.putBoolean("firststart", false);
            editor.commit();

            Intent intent = new Intent();
            intent.setClass(getApplicationContext(), IndexViewPagerActivity.class);
            startActivity(intent);
            finish();
        } else {
            getWindow().getDecorView().postDelayed(new Runnable() {
                @Override
                public void run() {
                    Intent intent = new Intent();
                    UserInfo userInfo = AppContext.getCurrentUser();
                    if (!TextUtils.isEmpty(userInfo.getAccessToken()) && userInfo.getUserId() != 0 && userInfo.isRegisterCompany()) {
                        intent.setClass(getApplicationContext(), MainActivity.class);
                    } else {
                        AppContext.clearLoginInfo(IndexActivity.this);
                        intent.setClass(getApplicationContext(), LoginActivity.class);
                    }
                    startActivity(intent);
                    finish();
                }
            }, 2000);
        }
    }

}